// pages/news/news.js
var WebIM = require('../../utils/WebIM.js');
var WebIM = WebIM.default;
const API = require('../../common/constant');
const util = require('../../utils/util');
const app = getApp();
Page({
  hxloign: function () {
    var options = {
      apiUrl: WebIM.config.apiURL,
      user: this.data.myName,
      pwd: this.data.password,
      grant_type: 'password',
      appKey: WebIM.config.appkey
    }
    WebIM.conn.open(options)
  },
  onLoad: function (options) {
    if (!app.globalData.hasUserInfo) {
      return;
    }
    if (wx.hideTabBarRedDot) {
      wx.hideTabBarRedDot({
        index: 3
      })
    } 
    if (!app.isPhoneLogin()) {
      app.showUserInfo('您还没有登录，暂不能查看，2s后自动为您跳到登录页面', 'none', 1000)
      setTimeout(function () {
        wx.redirectTo({
          url: '../loginAndRegister/loginAndRegister'
        });
      }, 2000)
    }
  },
  onShow: function () {
    if (!app.globalData.hasUserInfo) {
      app.showUserInfo('请授权，2s后自动跳转首页', 'none', 2000);
      setTimeout(function () {
        wx.switchTab({
          url: '../index/index'
        })
      }, 2000)
      return;
    }
    if (wx.getStorageSync('sessionId')) {
      let myUserInfo = wx.getStorageSync('userInfo');
      this.setData({
        myName: myUserInfo.userId + '',
        selfHeadImgUrl: myUserInfo.avatarUrl,
        password: myUserInfo.password,
      })
      this.hxloign();
      this.getMemberList();
      this.isHaveNews();
    }
  },
  isHaveNews() {
    let that = this;
    util.http({
      url: API.URL.MESSAGE.SELECT_ISMESSAGENEW,
      success(res) {
        console.log('获取是否有新消息成功', res);
        that.setData({
          isFriendNew: res.data.bussData.isFriendNew,
          isInvitedinnerNew: res.data.bussData.isInvitedinnerNew,
          isMessageNew: res.data.bussData.isMessageNew
        })
      },
      fail() {
        console.log('获取是否有新消息失败', res)
      }
    })
  },
  setChatMemberListCache(chatMemberName) {
    let chatMemberList = wx.getStorageSync('chatMemberList') || [];
    if (!chatMemberList.includes(chatMemberName)) {
      chatMemberList.push(chatMemberName);
    }
    console.log('chatMemberList', chatMemberList);
    wx.setStorage({
      key: 'chatMemberList',
      data: chatMemberList
    })
  },
  receiveMsg: function (message, type) {
    let that = this;
    if (type == 'txt') {
      var value = WebIM.parseEmoji(message.data.replace(/\n/mg, ''))
    } else if (type == 'emoji') {
      var value = message.data
    }
    let msgData = {
      'info': {
        'from': message.from,
        'to': message.to
      },
      'myName': message.from,
      'yourname': message.to,
      'msg': {
        'type': type,
        'data': value,
        url: message.url
      },
      'style': '',
      'time': message.ext.time,
      'mid': message.type + message.id
    };
    var chatMemberName = 'from' + message.from + "to" + message.to;
    var chatMsgObj = wx.getStorageSync(chatMemberName) || {};
    var chatMsg = chatMsgObj.chatMsg || [];
    chatMsg.push(msgData);

    let noSeeCount = chatMsgObj.noSeeCount || 0;
    if (!this.data[chatMemberName]) {
      this.setData({
        [chatMemberName]: noSeeCount
      })
    }
    noSeeCount = this.data[chatMemberName];
    console.log(noSeeCount);
    const chatMsgCache = {
      noSeeCount: noSeeCount + 1,
      yourNickname: message.ext.nickname,
      yourHeadImgUrl: message.ext.headImgUrl,
      yourname: message.from,
      chatMsg: chatMsg
    };
    this.setData({
      [chatMemberName]: noSeeCount + 1
    })
    wx.setStorageSync(chatMemberName, chatMsgCache);
    that.setChatMemberListCache(chatMemberName);
    this.getMemberList();
  },
  receiveImage(message, type) {
    var that = this;
    var myName = this.data.myName;
    if (message) {
      var time = message.ext.time;
      var msgData = {
        info: {
          from: message.from,
          to: message.to
        },
        myName: message.from,
        yourname: message.to,
        msg: {
          type: type,
          data: message.url
        },
        style: '',
        time: time,
        mid: 'img' + message.id
      }
      var chatMemberName = 'from' + message.from + "to" + message.to;
      var chatMsgObj = wx.getStorageSync(chatMemberName) || {};
      var chatMsg = chatMsgObj.chatMsg || [];
      chatMsg.push(msgData);
      let noSeeCount = chatMsgObj.noSeeCount || 0;
      if (!this.data[chatMemberName]) {
        this.setData({
          [chatMemberName]: noSeeCount
        })
      }
      noSeeCount = this.data[chatMemberName];
      console.log(noSeeCount);
      const chatMsgCache = {
        noSeeCount: noSeeCount + 1,
        yourNickname: message.ext.nickname,
        yourHeadImgUrl: message.ext.headImgUrl,
        yourname: message.from,
        chatMsg: chatMsg
      };
      this.setData({
        [chatMemberName]: noSeeCount + 1
      })
      wx.setStorageSync(chatMemberName, chatMsgCache);
      that.setChatMemberListCache(chatMemberName);
      this.getMemberList();
    }
  },
  getMemberList: function () {
    let chatMemberList = wx.getStorageSync('chatMemberList') || [];
    console.log('得到的聊天列表为: ', chatMemberList);
    let myName = wx.getStorageSync('userInfo').userId;
    let chatList = [];
    let count = 0;
    if (chatMemberList.length >= 1) {
      for (let i = 0, len = chatMemberList.length; i < len; i++) {
        let itemName = chatMemberList[i];
        let index = itemName.indexOf('to');
        if (itemName.slice(index + 2) == myName) {
          chatList[count] = wx.getStorageSync(chatMemberList[i]);
          count++;
        }
      }
    }
    this.setData({
      chatList: chatList
    })
  },
  gotoChat: function (e) {
    let num = e.currentTarget.dataset.num
    let itemName = 'from' + this.data.chatList[num].yourname + 'to' + this.data.myName;
    let chatList = this.data.chatList;
    chatList[num].noSeeCount = 0;
    this.setData({
      [itemName]: 0,
      chatList: chatList
    })
    wx.setStorageSync(itemName, this.data.chatList[num]);
    let itemInfo = this.data.chatList[num];
    wx.navigateTo({
      url: `/pages/chat/chat?id=${itemInfo.yourname}&yourNickname=${itemInfo.yourNickname}&yourHeadImgUrl=${itemInfo.yourHeadImgUrl}`,
    })
  },
  deleteMessage(e) {
    let that = this;
    wx.showModal({
      title: '是否删除聊天',
      content: '删除后，聊天内容也将一并删除',
      success: res => {
        if (res.confirm) {
          let num = e.currentTarget.dataset.num;
          let itemName = 'from' + that.data.chatList[num].yourname + 'to' + that.data.myName;
          console.log(itemName);
          wx.removeStorageSync(itemName);
          let chatMemberList = wx.getStorageSync('chatMemberList');
          for (let i = 0, len = chatMemberList.length; i < len; i++) {
            if (chatMemberList[i] == itemName) {
              chatMemberList.splice(i, 1);
            }
          }
          console.log(chatMemberList);
          wx.setStorageSync('chatMemberList', chatMemberList);
          that.getMemberList();
        }
      }
    })
  },
})